/* eslint-disable react/jsx-indent */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Row, Col, Select, Radio, Input, Divider } from 'antd';
import router from 'umi/router';
import styles from '@/utils/utils.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import downloadFile, { getFileName } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';
import AddEmpInfor from '../../SocialService/SocialCard/AddEmpInfor';
import AddMatInfor from '../../SocialService/SocialCard/AddMatInfor';

const FormItem = Form.Item;
const formItemLayouts = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
    xxl: { span: 6 },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
    xxl: { span: 18 },
  },
};
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 9,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: { span: 7 },
  },
};
const { Option } = Select;
const RadioGroup = Radio.Group;
@connect(({ handle: { updatedetail, coltFlag }, loading }) => ({
  updatedetail,
  coltFlag,
  loading: loading.effects['handle/fetchUpdateDetail'],
}))
class UpdateArchives extends Component {
  state = {};

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { insSerHdlId } = location.query;
    this.setState({
      tabKey: location.query.submitFlag,
    });
    dispatch({
      type: 'handle/fetchUpdateDetail',
      payload: { insSerHdlId },
    });
  }

  onSelectData = element => {
    const { elementArr, dispatch } = this.props;
    dispatch({
      type: 'handle/matInfor',
      payload: { elementArr, element },
    });
    if (+element.inpType === 9 && Number(element.down) === 1) {
      if (element.downfile.response) {
        if (element.downfile.response.success) {
          this.downLoad(element.downfile.response.data);
        }
      } else {
        this.downLoad(element.downfile.uid.concat('|').concat(element.downfile.name));
      }
    }
  };

  downLoad = item => {
    const file = item.split('|');
    downloadFile({ fileId: file[0], fileName: getFileName(file[1]) });
  };

  refunds = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'handle/refunds',
      payload: { refundFlag: e.target.value },
    });
  };

  saveUpdate = () => {
    const { location, updatedetail, form } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/update')[0];
    const { insCardHdl } = updatedetail;
    const insCardHdlData = insCardHdl;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      const temp = values;
      if (err) return;
      const matlist = [];
      const insSerHdl = {};
      Object.keys(values).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(temp[key].inpType) === '9') {
            let file = '';

            if (temp[key].fileList && temp[key].fileList.length) {
              temp[key].fileList.forEach(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                } else if (!item.responss) {
                  file += item.uid
                    .concat('|')
                    .concat(item.name)
                    .concat(',');
                }
              });
              temp[key].inpVal = file ? file.slice(0, file.length - 1) : '';
            }
          }
          temp[key].pkgPageDetailId = temp[key].pageDetailId;
          matlist.push(temp[key]);
        } else if (key === 'copyFiles') {
          insSerHdl.copyFiles = temp[key];
        } else if (key === 'masterFiles') {
          insSerHdl.masterFiles = temp[key];
        }
      });
      insSerHdl.matFlag = +insCardHdlData.submitFlag === 2 ? temp.matFlag : 1;
      insSerHdl.insSerHdlId = insCardHdlData.insSerHdlId;
      insSerHdl.vno = insCardHdlData.vno;
      insSerHdl.sendId = insCardHdlData.sendId;
      insSerHdl.source = insCardHdlData.source;
      insSerHdl.serTypeId = insCardHdlData.serTypeId;
      insSerHdl.refundFlag = insCardHdlData.refundFlag;
      if (Number(insCardHdlData.refundFlag) === 1) {
        insSerHdl.payeeBankcardNo = temp.payeeBankcardNo;
        insSerHdl.payeeBankOfDepo = temp.payeeBankOfDepo;
        insSerHdl.payeeName = temp.payeeName;
      }
      insSerHdl.submitFlag = '1';
      const param = {
        matlist,
        insSerHdl,
      };
      const { dispatch } = this.props;
      dispatch({
        type: 'handle/updateList',
        payload: param,
        callback: response => {
          if (response) {
            router.push(`${tempUrl}/index`);
          }
        },
      });
    });
  };

  save = () => {
    const { location, updatedetail, form } = this.props;
    const { pathname } = location;
    const { tabKey } = this.state;
    const tempUrl = pathname.split('/update')[0];
    const { insCardHdl } = updatedetail;
    const insCardHdlData = insCardHdl;
    form.validateFieldsAndScroll({ force: true }, (err, values) => {
      if (err) return;
      const temp = values;
      const matlist = [];
      const insSerHdl = {};
      Object.keys(values).forEach(key => {
        if (key.indexOf('_') !== -1) {
          if (String(temp[key].inpType) === '9') {
            let file = '';

            if (temp[key].fileList && temp[key].fileList.length) {
              temp[key].fileList.forEach(item => {
                if (item.response && item.response.success) {
                  file += `${item.response.data},`;
                } else if (!item.responss) {
                  file += item.uid
                    .concat('|')
                    .concat(item.name)
                    .concat(',');
                }
              });
              temp[key].inpVal = file ? file.slice(0, file.length - 1) : '';
            }
          }
          temp[key].pkgPageDetailId = temp[key].pageDetailId;
          matlist.push(temp[key]);
        } else if (key === 'copyFiles') {
          insSerHdl.copyFiles = temp[key];
        } else if (key === 'masterFiles') {
          insSerHdl.masterFiles = temp[key];
        }
      });

      insSerHdl.matFlag = Number(insCardHdlData.submitFlag) === 2 ? temp.matFlag : 1;
      insSerHdl.insSerHdlId = insCardHdlData.insSerHdlId;
      insSerHdl.vno = insCardHdlData.vno;
      insSerHdl.sendId = insCardHdlData.sendId;
      insSerHdl.source = insCardHdlData.source;
      insSerHdl.serTypeId = insCardHdlData.serTypeId;
      insSerHdl.refundFlag = insCardHdlData.refundFlag;
      if (String(insCardHdlData.refundFlag) === '1') {
        insSerHdl.payeeBankcardNo = temp.payeeBankcardNo;
        insSerHdl.payeeBankOfDepo = temp.payeeBankOfDepo;
        insSerHdl.payeeName = temp.payeeName;
      }
      insSerHdl.submitFlag = Number(tabKey) === 2 ? '2' : '1';
      const param = {
        matlist,
        insSerHdl,
      };
      const { dispatch } = this.props;
      dispatch({
        type: 'handle/updateList',
        payload: param,
        callback: response => {
          if (response) {
            router.push(`${tempUrl}/index`);
          }
        },
      });
    });
  };

  close = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/update')[0];
    router.push(`${tempUrl}/index`);
  };

  checkElement = (rule, value, callback) => {
    let tip = '';
    switch (Number(value.inpType)) {
      case 1:
        tip = `请输入不超过30个字的${value.matName}`;
        break;
      case 9:
        tip = `请上传${value.matName}`;
        break;
      case 3:
        tip = `请输入不超过300个字的${value.matName}`;
        break;
      default:
        tip = `请选择${value.matName}`;
        break;
    }
    if (
      Number(value.inpType) !== 9
        ? rule.required && !value.inpVal
        : rule.required && !(value.fileList && value.fileList.length)
    ) {
      callback(tip);
    } else if (Number(value.inpType) === 1 || Number(value.inpType) === 3) {
      if (rule.max < (value.inpVal && value.inpVal.length)) {
        callback(tip);
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  render() {
    const { updatedetail, coltFlag, form } = this.props;
    const { getFieldDecorator } = form;
    const { tabKey } = this.state;
    const { empSendInfoVo, empBaseInfoVo, elementArr, matFileDictItem, insCardHdl } = updatedetail;
    const { submitFlag } = insCardHdl;
    const max = val => {
      if (val === 1) return 30;
      if (val === 3) return 300;
      return null;
    };
    const renderElem = ele =>
      ele && ele.length
        ? ele.map(element => (
            <div key={element.pageDetailId}>
              <Col span={8}>
                <FormItem
                  {...formItemLayouts}
                  key={element.pageDetailId}
                  label={<span> {element.matName}</span>}
                >
                  {getFieldDecorator(`mat_${element.pageDetailId}`, {
                    rules: [
                      {
                        required: Number(element.reqFlag) === 1,
                        validator: this.checkElement,
                        max: max(+element.inpType),
                      },
                    ],
                    initialValue: element,
                  })(<AddMatInfor onChange={this.onSelectData} />)}
                </FormItem>
              </Col>
            </div>
          ))
        : null;
    return (
      <PageHeaderWrapper>
        <AddEmpInfor empSendInfoVo={empSendInfoVo} empBaseInfoVo={empBaseInfoVo} />
        <div className={styles.stepsAction}>
          <Card title={<span>业务信息</span>}>
            <Form layout="inline">
              <Row>
                <Col span={8}>
                  <FormItem label="服务类型:">
                    {insCardHdl && insCardHdl.serTypeIdName ? insCardHdl.serTypeIdName : null}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="是否有返款:">
                    {getFieldDecorator('refundFlag', {
                      rules: [
                        {
                          required: true,
                          message: '请选择是否有返款',
                        },
                      ],
                      initialValue:
                        insCardHdl && insCardHdl.refundFlag ? `${insCardHdl.refundFlag}` : null,
                    })(
                      <RadioGroup onChange={this.refunds}>
                        <Radio value="2">无返款</Radio>
                        <Radio value="1">有返款</Radio>
                      </RadioGroup>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Form>
            <Form>
              {String(insCardHdl.refundFlag) === '1' ? (
                <Row
                  style={{
                    backgroundColor: '#fafafa',
                    height: 60,
                    marginTop: 5,
                  }}
                >
                  <Col span={8}>
                    <FormItem
                      {...formItemLayouts}
                      label="收款方信息:"
                      style={{
                        marginTop: 15,
                        marginLeft: -20
                      }}
                    >
                      {getFieldDecorator('payeeName', {
                        rules: [
                          {
                            required: false,
                            message: '请输入不超过50个字符的收款方信息',
                            max: 50,
                          },
                        ],
                        initialValue: insCardHdl.payeeName ? insCardHdl.payeeName : null,
                      })(<Input placeholder="请输入收款方信息" />)}
                    </FormItem>
                  </Col>

                  <Col span={8} className={styles.triangle}>
                    <FormItem
                      {...formItemLayouts}
                      label="收款方银行账号:"
                      style={{
                        marginTop: 15,
                      }}
                    >
                      {getFieldDecorator('payeeBankcardNo', {
                        rules: [
                          {
                            required: false,
                            message: '请输入不超过30个字符的收款方银行账号',
                            pattern: /^[0-9]{1,30}$/,
                          },
                        ],
                        initialValue: insCardHdl.payeeBankcardNo
                          ? insCardHdl.payeeBankcardNo
                          : null,
                      })(<Input placeholder="请输入收款方银行账号" />)}
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem
                      {...formItemLayouts}
                      label="开户行信息:"
                      style={{
                        marginTop: 15,
                      }}
                    >
                      {getFieldDecorator('payeeBankOfDepo', {
                        rules: [
                          {
                            required: false,
                            message: '请输入不超过50个字符的开户行信息',
                            max: 50,
                          },
                        ],
                        initialValue: insCardHdl.payeeBankOfDepo
                          ? insCardHdl.payeeBankOfDepo
                          : null,
                      })(<Input placeholder="请输入开户行信息" />)}
                    </FormItem>
                  </Col>
                </Row>
              ) : null}
            </Form>
            {String(coltFlag) === '1' && (
              <div>
                <Divider />
                <Form>
                  <div>
                    {matFileDictItem && matFileDictItem.length ? (
                      <div>
                        <div>
                          <Col span={8}>
                            <FormItem {...formItemLayouts} label="原件材料:">
                              {getFieldDecorator('masterFiles', {
                                rules: [
                                  {
                                    required: false,
                                    message: '请选择原件材料',
                                  },
                                ],
                                initialValue:
                                  insCardHdl && insCardHdl.masterFile
                                    ? insCardHdl.masterFile
                                    : undefined,
                              })(
                                <HOCSelect
                                  style={{ width: '100%' }}
                                  mode="multiple"
                                  placeholder="请选择原件材料"
                                  onChange={this.aaa}
                                >
                                  {matFileDictItem && matFileDictItem.length
                                    ? matFileDictItem.map(options => (
                                        <Option key={options.itemCode}>{options.itemName}</Option>
                                      ))
                                    : null}
                                </HOCSelect>
                              )}
                            </FormItem>
                          </Col>
                        </div>
                        <div>
                          <Col span={8}>
                            <FormItem {...formItemLayouts} label="复印件材料:">
                              {getFieldDecorator('copyFiles', {
                                rules: [
                                  {
                                    required: false,
                                    message: '请选择复印件材料',
                                  },
                                ],
                                initialValue:
                                  insCardHdl && insCardHdl.copyFile
                                    ? insCardHdl.copyFile
                                    : undefined,
                              })(
                                <HOCSelect
                                  style={{ width: '100%' }}
                                  mode="multiple"
                                  placeholder="请选择复印件材料"
                                >
                                  {matFileDictItem && matFileDictItem.length
                                    ? matFileDictItem.map(options => (
                                        <Option key={options.itemCode}>{options.itemName}</Option>
                                      ))
                                    : null}
                                </HOCSelect>
                              )}
                            </FormItem>
                          </Col>
                        </div>
                      </div>
                    ) : null}
                    <div>
                      {renderElem(elementArr)}
                      {Number(submitFlag) === 2 ? (
                        <div>
                          <Col span={14} offset={1}>
                            <FormItem {...formItemLayout} label="材料是否完整:">
                              {getFieldDecorator('matFlag', {
                                rules: [
                                  {
                                    required: true,
                                    message: '请选择材料是否完整',
                                  },
                                ],
                                initialValue:
                                  insCardHdl && insCardHdl.matFlag
                                    ? `${insCardHdl.matFlag}`
                                    : undefined,
                              })(
                                <RadioGroup>
                                  <Radio value="1">是</Radio>
                                  <Radio value="2">否</Radio>
                                </RadioGroup>
                              )}
                            </FormItem>
                          </Col>
                        </div>
                      ) : null}
                    </div>
                  </div>
                </Form>
              </div>
            )}
          </Card>
        </div>
        <FooterToolbar style={{ width: '100%' }}>
          <Button onClick={() => this.close()}>取消</Button>
          <Button type="primary" onClick={() => this.save()} style={{ marginLeft: 8 }}>
            保存
          </Button>
          {Number(tabKey) === 2 ? (
            <Button type="primary" onClick={() => this.saveUpdate()} style={{ marginLeft: 8 }}>
              保存并提交运行
            </Button>
          ) : null}
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

const UpdateArchivesform = Form.create()(UpdateArchives);
export default UpdateArchivesform;
